package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.animalNumber.entity.AnimalNumber;
import com.antdesignbackend.backend.animalNumber.service.AnimalNumberService;
import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.returnResult.ReturnCode;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.common.web.BaseController;
import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.entity.Enterprise;
import com.antdesignbackend.backend.entity.HarmlessReport;
import com.antdesignbackend.backend.entity.Production;
import com.antdesignbackend.backend.entity.entityVo.HarmlessReportVo;
import com.antdesignbackend.backend.service.EnterpriseService;
import com.antdesignbackend.backend.service.HarmlessReportService;
import com.antdesignbackend.backend.service.ProductionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/harmlessReportSpeech")
public class HarmlessReportSpeechController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private Integer menuId;

    @Autowired
    HarmlessReportService harmlessReportService;
    @Autowired
    ProductionService productionService;
    @Autowired
    AnimalNumberService animalNumberService;
    @Autowired
    EnterpriseService enterpriseService;
    @GetMapping("/index")
    @AuthToken
    public String ProductionIndex( Model model) {
        model.addAttribute("type",getLoginAnimalTypes());
        return "harmless/harmlessReportSpeech";
    }

    /**
     * 分页查询
     * @param harmlessReportVo
     * @return
     */
    @PostMapping("/tableSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearch(@RequestBody HarmlessReportVo harmlessReportVo, HttpServletRequest request) {
        ReturnVO result = new ReturnVO();
        List<HarmlessReportVo> datalist=new ArrayList<>();
        try {
            QueryWrapper<HarmlessReportVo> queryWrapper = new QueryWrapper<>();
            QueryWrapper<Enterprise> enterpriseQueryWrapper=new QueryWrapper<>();
            queryWrapper.eq("eid",getLoginEnterpriseId());
            queryWrapper.eq("status",0);
            if (harmlessReportVo.getTimeInterval() != null && !harmlessReportVo.getTimeInterval().equals("")){
                String[] str=harmlessReportVo.getTimeInterval().split(" - ");
                String star=str[0];
                String end=str[1];
                queryWrapper.between("declareTime",star,end);
            }
            queryWrapper.orderByDesc("declareTime");
            int total=harmlessReportService.count(queryWrapper);
            result.setTotal(total);
            //再查询
            if(total>0)
            {
                datalist= harmlessReportService.search(queryWrapper,new Page<>(harmlessReportVo.getPageIndex(),harmlessReportVo.getPageSize()));
                for (HarmlessReportVo harmlessReportVo1:datalist){
                    if (harmlessReportVo1.getImg() != null && !harmlessReportVo1.getImg().equals("")){
                        harmlessReportVo1.setImg(WebConfig.host+"images/"+harmlessReportVo1.getImg());
                    }
                    if (harmlessReportVo1.getDeclareImage() != null && !harmlessReportVo1.getDeclareImage().equals("")){
                        harmlessReportVo1.setDeclareImageUrl(WebConfig.host+"images/"+harmlessReportVo1.getDeclareImage());
                    }
                    if (harmlessReportVo1.getHarmlessId() != null && !harmlessReportVo1.getHarmlessId().equals("")){
                        enterpriseQueryWrapper.eq("EnterpriseId",harmlessReportVo1.getHarmlessId());
                        Enterprise enterprise=enterpriseService.getOne(enterpriseQueryWrapper);
                        harmlessReportVo1.setHarmlessName(enterprise.getEnterpriseName());
                    }
                }
                //得到当前菜单具备的功能权限
                //获得当前角色
//                Object roleID = request.getSession().getAttribute("RoleID");
//                List<Button> list = permissionService.filterPermission(String.valueOf(roleID), menuId);
//                datalist.forEach(model -> model.setButtonList(list));
            }
            result.setData(datalist);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return result;
    }

    /**
     * 上报
     * @param harmlessReport
     * @return
     */
    @PostMapping("/edit")
    @ResponseBody
    @AuthToken
    public ReturnVO edit(@RequestBody HarmlessReport harmlessReport) {
        ReturnVO returnVO = new ReturnVO();
        try {
            //设置上报时间
            harmlessReport.setCreateTime(new Date());
            //设置上报人
            harmlessReport.setUserId(getLoginUserId());
            //获得处理途径 设置状态
            if (harmlessReport.getDhannel() == 0){ //自行处理，设置为已处理
                harmlessReport.setStatus(3);
                //添加死淘记录
                Production production = new Production();
                production.setUid(getLoginUserId());
                production.setEid(getLoginEnterpriseId());
                production.setChangeTime(new Date());
                production.setSituation("死淘");
                production.setAnimalType(getLoginAnimal());

                //判断动物类型
                if (getLoginAnimalTypes() == 1){
                    production.setMale(harmlessReport.getSpecies());
                    production.setFemale(harmlessReport.getReserve());
                    production.setBreedFemale(harmlessReport.getMenstruation());
                    production.setLactation(harmlessReport.getLactation());
                    production.setConservation(harmlessReport.getConservation());
                    production.setGrow(harmlessReport.getCommodity());
                }else {
                    production.setNumber(harmlessReport.getLivestock());
                }
                productionService.save(production);
                //修改动物数量
                //获得原有的值
                if (getLoginAnimalTypes() == 1){
                    AnimalNumber animalNumber = animalNumberService.getById(harmlessReport.getBatch());
                    if (animalNumber != null){
                        animalNumber.setSpecies(animalNumber.getSpecies() - harmlessReport.getSpecies());
                        animalNumber.setReserve(animalNumber.getReserve() - harmlessReport.getReserve());
                        animalNumber.setMenstruation(animalNumber.getMenstruation() - harmlessReport.getMenstruation());
                        animalNumber.setLactation(animalNumber.getLactation() - harmlessReport.getLactation());
                        animalNumber.setConservation(animalNumber.getConservation() - harmlessReport.getConservation());
                        animalNumber.setCommodity(animalNumber.getCommodity() - harmlessReport.getCommodity());
                        animalNumberService.updateById(animalNumber);
                    }
                }else {
                    QueryWrapper<AnimalNumber> wrapper = new QueryWrapper<>();
                    wrapper.eq("channel",1);
                    wrapper.eq("eid",getLoginEnterpriseId());
                    List<AnimalNumber> list = animalNumberService.list(wrapper);
                    if (!list.isEmpty()){
                        AnimalNumber animalNumber = list.get(0);
                        animalNumber.setLivestock(animalNumber.getLivestock() - harmlessReport.getLivestock());
                        animalNumberService.updateById(animalNumber);
                    }
                }

            }
            if (harmlessReport.getDhannel() == 1){ //集中处理，设置为待运输
                //设置无害化处理企业
                Enterprise enterprise = enterpriseService.getById(getLoginEnterpriseId());
                if (enterprise != null && enterprise.getHarmlessId() != null){
                    harmlessReport.setStatus(1);
                    harmlessReport.setHarmlessId(enterprise.getHarmlessId());
                }else {
                    returnVO.setCode("500");
                    returnVO.setMessage("该企业没有绑定的无害化企业，请联系管理员！");
                    return returnVO;
                }
            }
            harmlessReportService.updateById(harmlessReport);
            returnVO.setCode("200");
            returnVO.setMessage("操作成功！");
            return returnVO;
        } catch (Exception e) {
            logger.error(e.getMessage());
            returnVO.setCode("500");
            returnVO.setMessage(e.getMessage());
            return returnVO;
        }
    }
}
